/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-11 17:52:20
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-11-05 15:37:45
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Alert,
  AutoComplete,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  List,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Tag,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './enterprise.less';

const FormItem = Form.Item;

const { Option } = Select;

@connect(({ companyStorePage, dict, contractList, loading }) => ({
  companyStorePage,
  dict,
  contractList,
  loading: loading.models.companyStorePage,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    dataSource: [], // 企业名称 数据源
    result: [], // 企业名称 自动匹配结果
    companyId: '', // 企业id
    contractId: '', // 合同id
    selectedRows: [],
    selectedStores: [],
    contarctValue: '',
    type: 'add',
  };

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;

    let companyId = '';
    let contractId = '';
    if (query) {
      ({ companyId } = query);
      ({ contractId } = query);
      const { companyName, contractTitle } = query;
      this.setState({
        type: 'edit',
        companyName,
        contractTitle,
        companyId,
        contractId,
      });
    }

    dispatch({
      type: 'companyStorePage/getParams',
    });

    // 查询公司
    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return <Option key={v.id}>{v.name}</Option>;
        });
        this.setState({
          dataSource: newList,
          result: newList,
        });
      },
    });

    dispatch({
      type: 'contractList/getList',
      payload: { companyId },
    });

    // 查询已选门店;
    dispatch({
      type: 'companyStorePage/getCompanyStoreList',
      payload: {
        companyId,
        contractId,
      },
      callback: res => {
        if (res.data) {
          this.mergeSelectList(res.data);
        }
      },
    });

    // 查询门店
    // dispatch({
    //   type: 'dict/dictStoreList',
    //   payload: {
    //     cityId: '',
    //     institutionId: '',
    //     name: '',
    //     provinceId: '',
    //   },
    // });

    // 清空门店;
    dispatch({
      type: 'dict/dictClearStoreList',
    });

    // 查询体检机构
    dispatch({
      type: 'dict/dictInstitutionList',
      payload: {},
    });

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });
  }

  onSelect = v => {
    const { dispatch } = this.props;
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });

    this.setState(
      {
        companyId: v,
        contarctValue: '',
      },
      () => {
        this.searchSelectedStore();
      }
    );
  };

  onChangeH = (v, t) => {
    const {
      props: { children },
    } = t;
    this.setState(
      {
        contractId: v,
        contarctValue: children,
      },
      () => {
        this.searchSelectedStore();
      }
    );
  };

  onChangeP = v => {
    const { dispatch } = this.props;
    // 查询城市
    dispatch({
      type: 'dict/dictCityList',
      payload: { provinceId: v },
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { companyId, contractId } = this.state;
    form.resetFields();
    dispatch({
      type: 'companyStorePage/getCompanyStoreList',
      payload: {
        companyId,
        contractId,
      },
      callback: res => {
        if (res.data) {
          this.mergeSelectList(res.data);
        }
      },
    });
  };

  // 查询门店
  handleSearchForm = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'dict/dictStoreList',
        payload: { ...fieldsValue },
      });
    });
  };

  // 查询已选门店
  searchSelectedStore = () => {
    const { dispatch } = this.props;
    const { companyId, contractId } = this.state;
    dispatch({
      type: 'companyStorePage/getCompanyStoreList',
      payload: {
        companyId,
        contractId,
      },
      callback: res => {
        if (res.data) {
          this.mergeSelectList(res.data);
        }
      },
    });
  };

  // 查询公司
  handleSearch = value => {
    const { dataSource } = this.state;
    const newList = dataSource.filter(v => v.props.children.indexOf(value) > -1);
    this.setState({ result: newList });
  };

  // 合并 选中
  mergeSelectList = d => {
    if (d instanceof Array) {
      const newList = d.map(val => {
        const v = val;
        v.key = `k${v.storeId}`;
        v.name = v.storeName;
        return v;
      });

      this.setState({
        selectedStores: newList,
        //selectedRows: newList,
      });
    }
  };

  handleSelectRows = rows => {
    const { selectedStores } = this.state;

    const keyList = selectedStores.map(k => {
      return k.key;
    });
    let newList = [];

    rows.map(v => {
      if (keyList.indexOf(v.key) < 0) {
        newList.push(v);
      }
    });

    this.setState({ selectedRows: rows, selectedStores: [...selectedStores, ...newList] });
  };

  closeTag = v => {
    const { selectedStores } = this.state;
    const newList = selectedStores.filter(item => item.key !== v.key);
    this.setState({ selectedStores: newList });
  };

  handleSubmit = () => {
    const { selectedRows, selectedStores, companyId, contractId, type } = this.state;
    const { dispatch } = this.props;
    const storeIds = selectedStores.map(v => v.storeId);
    const that = this;
    if (!companyId) {
      message.info('请选择企业');
      return;
    }
    if (!contractId) {
      message.info('请选择合同');
      return;
    }


    dispatch({
      type: 'companyStorePage/companyStoreAdd',
      payload: {
        companyId,
        contractId,
        storeIds: [...storeIds],
      },
      callback: res => {
        if (res.success) {
          if (res.success) {
            let secondsToGo = 3;
            const modal = Modal.success({
              title: type === 'add' ? '新增成功' : '修改成功',
              content: `将在${secondsToGo}秒后返回企业可体检门店列表`,
              okText: '知道了',
              handleOk: that.handleCancel,
            });
            const timer = setInterval(() => {
              secondsToGo -= 1;
              modal.update({
                content: `将在${secondsToGo}秒后返返回企业可体检门店列表`,
              });
            }, 1000);
            setTimeout(() => {
              clearInterval(timer);
              modal.destroy();
              dispatch(routerRedux.push('/Enterprise/company-storePage'));
            }, secondsToGo * 1000);
          } else {
            message.info(res.errorDesc);
          }
        } else {
          message.info(res.errorDesc);
        }
      },
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Enterprise/company-storePage'));
  };

  renderTags = () => {
    const { selectedRows, selectedStores } = this.state;
    const newList = selectedStores.map(v => {
      return (
        <Tag key={v.key} closable onClose={() => this.closeTag(v)}>
          {v.name}
        </Tag>
      );
    });
    return <div>{[...newList]}</div>;
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => <Option key={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => <Option key={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsI = () => {
    const {
      dict: { institutionList },
    } = this.props;
    const options = institutionList.map(v => <Option key={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => <Option key={v.id}>{v.title}</Option>);
    return options;
  };

  render() {
    const {
      loading,
      form,
      dict: { storeList },
      companyStorePage: { params },
    } = this.props;
    const { result, selectedRows, contarctValue, contractTitle, companyName, type } = this.state;
    const { getFieldDecorator } = form;

    const columns = [
      {
        title: '门店名称',
        dataIndex: 'name',
      },
      {
        title: '门店地址',
        dataIndex: 'address',
      },
    ];
    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <Alert message="企业信息" type="info" />
          <Row gutter={{ lg: 24 }}>
            <Col md={24} sm={24} style={{ marginTop: 10 }}>
              <span>*&nbsp;企业名称：&nbsp;</span>
              {type === 'add' ? (
                <AutoComplete
                  style={{ width: 300 }}
                  onSelect={this.onSelect}
                  onSearch={this.handleSearch}
                  placeholder="输入企业名称查询"
                >
                  {result}
                </AutoComplete>
              ) : (
                <span>{companyName}</span>
              )}
            </Col>
          </Row>
          <Row gutter={{ lg: 24 }}>
            <Col md={24} sm={24} style={{ marginTop: 10 }}>
              <span>*&nbsp;合同名称：&nbsp;</span>
              {type === 'add' ? (
                <Select
                  placeholder="请选择"
                  style={{ width: 300 }}
                  onChange={this.onChangeH}
                  autoClearSearchValue
                  allowClear
                  value={contarctValue}
                >
                  {this.renderOptionsH()}
                </Select>
              ) : (
                <span>{contractTitle}</span>
              )}
            </Col>
          </Row>
          <Alert message="添加门店" type="info" style={{ marginBottom: 10, marginTop: 10 }} />
          <Row>
            <Col span={14}>
              <Card
                title="门店搜索"
                bordered={false}
                style={{ borderRight: '1px solid rgb(232, 232, 232)' }}
              >
                <Form layout="inline" onSubmit={this.handleSearchForm}>
                  <Row>
                    <Col md={12} sm={24}>
                      <FormItem label="体检机构">
                        {getFieldDecorator('institutionId', {
                          initialValue: '',
                        })(
                          <Select placeholder="请选择" style={{ width: 150 }}>
                            {this.renderOptionsI()}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col md={12} sm={24}>
                      <FormItem label="门店名&#12288;">
                        {getFieldDecorator('name', {
                          initialValue: '',
                        })(<Input placeholder="" style={{ width: 150 }} />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={12} sm={24}>
                      <FormItem label="省份&#12288;&#12288;">
                        {getFieldDecorator('provinceId', {
                          initialValue: '',
                        })(
                          <Select
                            showSearch
                            onChange={this.onChangeP}
                            placeholder="请选择"
                            style={{ width: 150 }}
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                            {this.renderOptionsP()}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col md={12} sm={24}>
                      <FormItem label="城市&#12288;&#12288;">
                        {getFieldDecorator('cityId', {
                          initialValue: '',
                        })(
                          <Select placeholder="请选择" style={{ width: 150 }}>
                            {this.renderOptionsC()}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={24} sm={24}>
                      <div
                        style={{
                          overflow: 'hidden',
                          height: '40px',
                          lineHeight: '40px',
                        }}
                      >
                        <span
                          style={{
                            float: 'right',
                          }}
                        >
                          <Button type="primary" htmlType="submit">
                            查询
                          </Button>
                          <Button
                            style={{
                              marginLeft: 8,
                            }}
                            onClick={this.handleFormReset}
                          >
                            重置
                          </Button>
                        </span>
                      </div>
                    </Col>
                  </Row>
                </Form>
                <SimpleTable
                  selectedRows={selectedRows}
                  onSelectRow={this.handleSelectRows}
                  loading={loading}
                  data={{ list: storeList }}
                  columns={columns}
                  onChange=""
                  rowKey="key"
                />
              </Card>
            </Col>
            <Col span={10}>
              <Card title="已选门店" className={styles.tagContainer} bordered={false}>
                {this.renderTags()}
              </Card>
            </Col>
          </Row>
        </Card>
        <Divider />
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSubmit}>
            提交
          </Button>
          <Button type="" onClick={this.handleCancel}>
            返回
          </Button>
        </div>
      </PageHeaderLayout>
    );
  }
}
